package com.leyou.auth.service;

import com.leyou.auth.config.JwtProperties;
import com.leyou.auth.entity.ApplicationInfo;
import com.leyou.auth.mapper.ApplicationInfoMapper;
import com.leyou.common.auth.pojo.AppInfo;
import com.leyou.common.auth.pojo.Payload;
import com.leyou.common.auth.pojo.UserInfo;
import com.leyou.common.auth.utils.JwtUtils;
import com.leyou.common.exception.pojo.ExceptionEnum;
import com.leyou.common.exception.pojo.LyException;
import com.leyou.common.utils.CookieUtils;
import com.leyou.user.client.UserClient;
import com.leyou.user.entity.User;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class AuthService {

    @Autowired
    private UserClient userClient;

    @Autowired
    private JwtProperties jwtProp;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Autowired
    private ApplicationInfoMapper applicationInfoMapper;

    public void login(String username, String password, HttpServletRequest request, HttpServletResponse response) {
        //校验用户名和密码是否正确
        User user = userClient.findUserInfo(username, password);
        if(user==null){
            throw new LyException(ExceptionEnum.INVALID_USERNAME_PASSWORD);
        }
        //将User转成userInfo
        UserInfo userInfo = new UserInfo(user.getId(), username, "admin");
        //生成令牌并写入浏览器的cookie中
        createTokenToCookie(request, response, userInfo);
    }

    /**
     * 生成令牌并写入浏览器的cookie中
     */
    private void createTokenToCookie(HttpServletRequest request, HttpServletResponse response, UserInfo userInfo) {
        //生成token
        String token = JwtUtils.generateTokenExpireInMinutes(userInfo, jwtProp.getPrivateKey(), jwtProp.getCookie().getExpire());
        //将token写入浏览器的cookie中
        CookieUtils.newCookieBuilder()
                .request(request)
                .response(response)
                .name(jwtProp.getCookie().getCookieName())
                .value(token)
                .httpOnly(true)
                .domain(jwtProp.getCookie().getCookieDomain())
                .build();
    }

    public UserInfo verify(HttpServletRequest request, HttpServletResponse response) {
        //获取token
        String token = CookieUtils.getCookieValue(request, jwtProp.getCookie().getCookieName());
        //解析token
        Payload<UserInfo> payload = null;
        //获取用户信息
        UserInfo userInfo = null;
        try {
            payload = JwtUtils.getInfoFromToken(token, jwtProp.getPublicKey(), UserInfo.class);
            userInfo = payload.getUserInfo();
        }catch (Exception e){
            throw new LyException(ExceptionEnum.UNAUTHORIZED);
        }
        //获取token的id
        String tokenId = payload.getId();
        //查看token是否在黑名单
        if(redisTemplate.hasKey(tokenId)){
            throw new LyException(ExceptionEnum.UNAUTHORIZED);
        }
        //获取过期时间
        Date expTime = payload.getExpiration();
        //在过期时间基础上减去刷新token的时间来得到刷新token的时间点
        DateTime refreshDate = new DateTime(expTime).minusMinutes(jwtProp.getCookie().getRefreshTime());
        //如果刷新时间点在当前时间之前就刷新token
        if(refreshDate.isBeforeNow()){
            //生成令牌并写入浏览器的cookie中
            createTokenToCookie(request, response, userInfo);
        }
        return userInfo;
    }

    public void logout(HttpServletRequest request, HttpServletResponse response) {
        //获取token
        String token = CookieUtils.getCookieValue(request, jwtProp.getCookie().getCookieName());
        //解析token
        Payload<Object> payload = null;
        try {
            payload = JwtUtils.getInfoFromToken(token, jwtProp.getPublicKey());
        }catch (Exception e){
            //表示token已经失效了，无需做后续步骤了。
            return;
        }
        //获取token的id
        String tokenId = payload.getId();
        //获取token的有效期的剩余时间的毫秒数
        long remainTime = payload.getExpiration().getTime() - System.currentTimeMillis();
        //将token放入redis黑名单中
        redisTemplate.opsForValue().set(tokenId, "随便写", remainTime, TimeUnit.MILLISECONDS);
        //删除cookie
        CookieUtils.deleteCookie(jwtProp.getCookie().getCookieName(),
                jwtProp.getCookie().getCookieDomain(), response);
    }

    /**
     * 验证服务的id和密码是否正确
     */
    public Boolean isUsable(Long serverId, String serverPassword){
        //根据服务id查询服务对象
        ApplicationInfo applicationInfo = applicationInfoMapper.selectByPrimaryKey(serverId);
        if(applicationInfo==null){
            //表示服务id不正确
            return false;
        }
        //获取数据库中加密的密码
        String secret = applicationInfo.getSecret();
        //比对用户输入的密码和加密的加密是否是同一个
        if(!passwordEncoder.matches(serverPassword, secret)){
            //表示密码不正确
            return false;
        }
        return true;
    }

    public String appLogin(Long id, String secret) {
        //验证服务id和密码
        if(!isUsable(id, secret)){
            throw new LyException(ExceptionEnum.INVALID_SERVER_ID_SECRET);
        }
        //查询当前服务可以访问的服务列表
        List<Long> targetIds = applicationInfoMapper.findTargetIdById(id);
        //封装生成token的App对象
        AppInfo appInfo = new AppInfo(id, secret, targetIds);
        //生成token
        String token = JwtUtils.generateTokenExpireInMinutes(appInfo,
                jwtProp.getPrivateKey(),
                jwtProp.getApp().getExpire());
        return token;
    }
}
